package com.beargod.aubridge

import android.util.Base64
import android.util.Log
import com.google.protobuf.Message

/**
 *  处理器基类
 *
 *  响应请求时需要执行逻辑由处理器来完成
 */
public abstract class HandlerBase<TParam: Message, TResult: Message> {
    abstract val interfaceCode: Int
    abstract val paramClass: Class<TParam>
    abstract val resultClass: Class<TResult>

    suspend fun handle(order: Int, message: String): HandleResult<TResult> {
        val param = parse(message, paramClass) ?: return HandleResult.withError(ApiResultCode.InvalidBuffer)
        Log.i(TAG, "HandlerBase handle, interface: $interfaceCode, param: $param")
        val result = handleInternal(order, param)
        Log.i(TAG, "HandlerBase handle, interface: $interfaceCode, result: $result")
        return result
    }

    /**
     * 处理请求需要执行的逻辑
     *
     * @param order 序号，再次调用序号会不同
     * @param param 参数
     */
    protected abstract suspend fun handleInternal(order: Int, param: TParam): HandleResult<TResult>

    companion object {
        private const val TAG = "HandlerBase"
        private fun <TMessage: Message> parse(message: String, clazz: Class<TMessage>): TMessage? {
            try {
                val parser = clazz.getMethod("parseFrom", ByteArray::class.java)
                return parser.invoke(null, Base64.decode(message, Base64.DEFAULT)) as TMessage
            }catch (e: Exception) {
                Log.e(TAG, "Failed to parse message: $message, clazz: ${clazz.name}")
                return null
            }
        }
    }
}